package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Posts;
import com.ruoyi.system.domain.vo.PostsAuditVo;
import com.ruoyi.system.domain.vo.PostsCreateVo;
import com.ruoyi.system.domain.vo.PostsUpdateVo;
import com.ruoyi.system.dto.PostsDTO;
import com.ruoyi.system.dto.PostsStatisticsDTO;
import com.ruoyi.system.service.PostsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 动态帖子控制器
 *
 * 提供帖子列表、详情、创建、修改、删除、批量删除、审核、统计、导出等接口
 */
@RestController
@RequestMapping("/system/posts")
@Api("动态管理")
public class PostsController extends BaseController {
    @Autowired
    private PostsService postsService;

    /** 查询帖子列表（支持分页与条件过滤） */
    @ApiOperation("动态列表")
    @PreAuthorize("@ss.hasPermi('system:posts:list')")
    @GetMapping("/list")
    public TableDataInfo list(Posts posts) {
        startPage();
        List<PostsDTO> list = postsService.selectPostsList(posts);
        return getDataTable(list);
    }

    /** 获取帖子详情 */
    @ApiOperation("动态详情")
    @PreAuthorize("@ss.hasPermi('system:posts:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        PostsDTO dto = postsService.selectPostsById(id);
        return AjaxResult.success(dto);
    }

    /** 新增发布帖子 */
    @ApiOperation("发布动态")
    @PreAuthorize("@ss.hasPermi('system:posts:add')")
    @Log(title = "动态", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody PostsCreateVo vo) {
        int rows = postsService.insertPosts(vo);
        return toAjax(rows);
    }

    @ApiOperation("导出动态")
    @PreAuthorize("@ss.hasPermi('system:posts:export')")
    @Log(title = "动态", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Posts posts) {
        List<Posts> list = postsService.selectPostsEntityList(posts);
        ExcelUtil<Posts> util = new ExcelUtil<>(Posts.class);
        util.exportExcel(response, list, "动态数据");
    }

    /** 修改帖子内容与属性 */
    @ApiOperation("修改动态")
    @PreAuthorize("@ss.hasPermi('system:posts:edit')")
    @Log(title = "动态", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody PostsUpdateVo vo) {
        Posts p = new Posts();
        p.setId(vo.getId());
        p.setUserId(vo.getUserId());
        p.setContentText(vo.getContent());
        String tagsEditJoined = join(vo.getTags());
        if (tagsEditJoined == null && vo.getTagsStr() != null) {
            tagsEditJoined = vo.getTagsStr().replace(";", ",");
        }
        p.setTags(tagsEditJoined);
//        p.setLocation(vo.getLocation());
        p.setVisibility(vo.getVisibility());

        p.setStatus(vo.getStatus());
        p.setLikeCount(vo.getLikeCount());
        p.setCommentCount(vo.getCommentCount());
        p.setShareCount(vo.getShareCount());
//        p.setRewardCount(vo.getRewardCount());
        p.setRewardAmount(vo.getRewardAmount());
        p.setIsTop(vo.getIsTop());
        int rows = postsService.updatePosts(p);
        return toAjax(rows);
    }

    /** 删除单个帖子 */
    @ApiOperation("删除动态")
    @PreAuthorize("@ss.hasPermi('system:posts:remove')")
    @Log(title = "动态", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(postsService.deletePostsById(id));
    }

    /** 批量删除帖子 */
    @ApiOperation("批量删除动态")
    @PreAuthorize("@ss.hasPermi('system:posts:remove')")
    @Log(title = "动态", businessType = BusinessType.DELETE)
    @DeleteMapping("/batch")
    public AjaxResult removeBatch(@RequestBody Long[] ids) {
        return toAjax(postsService.deletePostsByIds(ids));
    }

    /** 审核帖子（通过/违规/恢复正常） */
    @ApiOperation("审核动态")
    @PreAuthorize("@ss.hasPermi('system:posts:edit')")
    @PutMapping("/audit")
    public AjaxResult audit(@Validated @RequestBody PostsAuditVo vo) {
        return toAjax(postsService.auditPost(vo));
    }

    /** 获取帖子统计数据 */
    @ApiOperation("统计数据")
    @PreAuthorize("@ss.hasPermi('system:posts:list')")
    @GetMapping("/statistics")
    public AjaxResult statistics() {
        PostsStatisticsDTO dto = postsService.getStatistics();
        return AjaxResult.success(dto);
    }

    /**
     * 数组拼接为逗号分隔字符串
     * 用于将前端 images/tags 的数组持久化为字符串存储
     */
    private String join(List<String> list) {
        if (list == null || list.isEmpty()) return null;
        return list.stream().map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.joining(","));
    }
}
